import React, { Component } from 'react'
import styles from './index.module.scss'
import MyNavBar from '../../components/MyNavBar'
import { WhiteSpace, WingBlank, Flex, Toast } from 'antd-mobile'
import { login } from '../../api/user'
import { setToken } from '../../utils/token'

class Login extends Component {
  constructor () {
    super()

    this.state = {
      username: 'test2',
      password: 'test2'
    }
  }

  /**
  changeUserName = e => {
    this.setState({
      username: e.target.value
    })
  }

  changePassword = e => {
    this.setState({
      password: e.target.value
    })
  }
   */

  changeValue = e => {
    this.setState({
      [e.target.name]: e.target.value
    })
  }

  userLogin = async () => {
    const res = await login(this.state)

    if (res.data.status === 400) {
      Toast.info(res.data.description, 1.5)
      return
    }

    Toast.info('登录成功~', 1)

    //1、保存到本地
    setToken(res.data.body.token)

    //2、返回上个页面
    const { location } = this.props
    if (location.state && location.state.from) {
      // [my,login,rent]
      // this.props.history.push(location.state.from)
      // [my,rent]
      this.props.history.replace(location.state.from)
    } else {
      this.props.history.goBack()
    }
  }

  render () {
    const { username, password } = this.state
    return (
      <div className={styles.root}>
        <MyNavBar>账号登录</MyNavBar>
        <WhiteSpace size='xl' />
        <WingBlank size='lg'>
          <div className={styles.formItem}>
            <input
              className={styles.input}
              value={username}
              name='username'
              onChange={this.changeValue}
              placeholder='请输入账号'
            />
          </div>
          <div className={styles.formItem}>
            <input
              className={styles.input}
              type='password'
              name='password'
              placeholder='请输入密码'
              onChange={this.changeValue}
              value={password}
            />
          </div>
          <div className={styles.formSubmit}>
            <div onClick={this.userLogin} className={styles.submit}>
              登录
            </div>
          </div>
          <Flex className={styles.backHome}>
            <Flex.Item>
              <a href='#/'>还没有账号，去注册~</a>
            </Flex.Item>
          </Flex>
        </WingBlank>
      </div>
    )
  }
}

export default Login
